package com.fl.nettydemo.c2;

import com.fl.nettydemo.handler.MyDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * 轮询组
 */
@Slf4j
@Component
public class EventLoopServer {
    public static void main(String[] args) {
        openServer();
    }

    //随启动器一起运行
    @PostConstruct
    public static void openServer() {
        DefaultEventLoop eventLoop = new DefaultEventLoop();
        new ServerBootstrap()
                //1.选择线程组
                //boss 和 worke
                //boss处理serversocketchannel accpet事件 worke处理socketchannel 读写事件
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                //2.选择通道类型
                .channel(NioServerSocketChannel.class)
                //3.创建处理读写的通道链接
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //4.解析转码字符流
                        ch.pipeline().addLast(new StringEncoder());
                        //5. 读取转码后的数据
                        ch.pipeline().addLast("handel1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                byte [] b = new byte[buf.readableBytes()];
                                buf.readBytes(b);
                                log.info("msg:{}",buf);
                                ctx.fireChannelRead(msg);
                            }
                        }).addLast(eventLoop, "handel2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info("msg:{}", buf.toString(StandardCharsets.UTF_8));
                                ctx.fireChannelRead(msg);
                            }
                        });
                    }
                }).bind(1000);
        System.out.println("开启服务器--端口：1000");
    }
}
